package basic.study.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName Mid56
 * @Description 合并区间
 * @Company inspur
 * @Author Kevin
 * @Date 2020/6/23 11:50
 * @Version 1.0
 */
public class Mid56 {
    class Solution {
        public int[][] merge(int[][] intervals) {
            List<int[]> res = new ArrayList<>();
            Arrays.sort(intervals, (a, b)->a[0]-b[0]);
            int i = 0;
            while (i < intervals.length) {
                int left = intervals[i][0];
                int right = intervals[i][1];
                //如果重叠则覆盖
                while (i < intervals.length -1 && intervals[i+1][0] <= right) {
                    i++;
                    right = Math.max(right, intervals[i][1]);
                }
                //添加结果
                res.add(new int[]{left, right});
                //继续下一个区间
                i++;
            }
            return res.toArray(new int[0][]);
        }
    }
}
